import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-components';
import * as React from 'react';
import { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import { useAsyncEffect } from 'ahooks';
import type { GithubIssueItem } from '../Building';
import { SelectProps, message } from 'antd';
import { postBuildingsEdit } from '../request';
import { useIntl } from '@umijs/max';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const BuildingsModal = (props: {
  visible: boolean;
  id: number;
  info: GithubIssueItem | null;
  onCancel: () => void;
  done: () => void;
}) => {
  const { visible, id, onCancel, done, info } = props;



  const intl = useIntl()

  // 表单操作源
  const formRef = useRef<ProFormInstance>(null);

  // 表单布局
  const formItemLayout = {
    labelCol: { span: 4 },
  };

  // 可选择楼层
  const options: SelectProps['options'] = [];
  for (let i = 1; i <= 50; i++) {
    const value = `${intl.formatMessage(
      { id: 'FixLock.layer' },
      { itemLayer: i }

    )}`;
    options.push({
      label: value,
      value,
      // disabled: i === 10,
    });
  }

  // 可选择楼栋
  const buildingOptions: SelectProps['options'] = []; 
  for (let i = 1; i <= 30; i++) {
    const value = `${intl.formatMessage(
      { id: 'FixLock.buildings' },
      { itemLayer: i }

    )}`;
    buildingOptions.push({
      label: value,
      value: i,
      key: i,
      // disabled: i === 10,
    });
  }

  // 楼栋切换时，自动设置楼栋名称--可修改
  const buildingChange = (e: any) => {
    // formRef.current?.setFieldsValue({ name: `第${e}号楼` });
    formRef.current?.setFieldsValue({
      name: intl.formatMessage(
        { id: 'FixLock.The buildings' },
        { itemLayer: e }

      )
    });
  };

  // 确认提交表单信息
  const onFinish = async (values: GithubIssueItem): Promise<boolean> => {
    await waitTime(500);
    // 处理修改时楼栋存在的问题
    if (values.bno[values.bno.length - 1] === '栋') {
      values.bno = values.bno.slice(0, -1);
    }

    // 发请求新增/修改楼栋信息----id存在时为修改，不存在传0为新增
    const res: any = await postBuildingsEdit({
      ...values,
      bno: values.bno,
      floor: values.floor.sort((a: any, b: any) => a.slice(0, -1) - b.slice(0, -1)).join(','),
      id: id ? id : 0,
    });
    if (res.code !== 0) return message.error(res.msg);
    message.success(res.msg);
    // 关闭弹窗
    onCancel();
    // 获取最新数据
    done();
    return true;
  };
  // 当id存在时代表修改，此时将原数据赋值给表单--再做修改
  useAsyncEffect(async () => {
    await waitTime(50);

    if (visible && id) {
      if (info) {
        formRef?.current?.setFieldsValue({
          bno: `${info.bno}${intl.formatMessage({id:"FixLock.building"})}`,
          name: info.name,
          floor: info.floor.split(','),
          remark: info.remark,
        });
      }
    }
  }, [visible, id]);

  return (
    <ModalForm<GithubIssueItem>
      {...formItemLayout}
      layout={'horizontal'}
      formRef={formRef}
      open={visible}
      title={id ? `${intl.formatMessage({id:"FixLock.Change the building"})}` : `${intl.formatMessage({id:"FixLock.New buildings"})}`}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => onCancel(),
      }}
      submitTimeout={2000}
      onFinish={(values) => onFinish(values)}
      width={'500px'}
    >
      <div style={{ marginTop: '40px' }}></div>
      <ProFormSelect
        width="md"
        name="bno"
        label={intl.formatMessage({id:"FixLock.Building No"})}
        options={buildingOptions}
        placeholder={intl.formatMessage({id:"FixLock.Please enter the building number"})}
        rules={[{ required: true, message: intl.formatMessage({id:"FixLock.Please enter the building number"})}]}
        onChange={buildingChange}
      />
      <ProFormText
        width="md"
        name="name"
        label={intl.formatMessage({id:"FixLock.name"})}
        placeholder={intl.formatMessage({id:'FixLock.Please enter a name'})}
        rules={[{ required: true, message: intl.formatMessage({id:'FixLock.Please enter a name'}) }]}
      />
      <ProFormSelect
        mode={'multiple'}
        width="md"
        name="floor"
        label={intl.formatMessage({id:'FixLock.Floor'})}
        options={options}
        placeholder={intl.formatMessage({id:"FixLock.Please select a floor"})}
        rules={[{ required: true, message: intl.formatMessage({id:"FixLock.Please select a floor"}) }]}
      />
      <ProFormTextArea
        name="remark"
        width="md"
        label={intl.formatMessage({id:'FixLock.remark'})}
        placeholder={intl.formatMessage({id:'FixLock.Please enter remarks'})}
      // rules={[{ required: true, message: '请输入备注' }]}
      />
    </ModalForm>
  );
};

export default BuildingsModal;
